package logic

import (
	"context"
	"fmt"
	"library/models/cache"
	"library/models/mysql"
	"library/pkg"

	"library/library/internal/svc"
	"library/library/library"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *library.RegisterRequest) (*library.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.Rdb.Get(l.ctx, "sendSms"+"register"+in.Mobile)
	if get.Val() != in.Sms {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	var user mysql.User
	mysql.DB.Where("account = ?", in.Mobile).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("已注册的用户无法重复注册")
	}

	user = mysql.User{
		Account:  in.Mobile,
		Password: pkg.Md5(in.Password),
	}

	mysql.DB.Debug().Create(&user)

	return &library.RegisterResponse{UserId: int64(user.ID)}, nil
}
